package com.flyqiu.form.extensions.convert.mapping;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.flyqiu.form.extensions.FlyQiuFormDataConvert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public abstract class FlyQiuBaseAvueMapper implements FlyQiuAvueMapper {
    protected JSONObject column;
    protected Map<String, Object> headers;
    protected String startHomeUrl;

    @Override
    public void init(FlyQiuFormDataConvert convert, JSONObject column) {
        if (StringUtils.isAllBlank(startHomeUrl)) {
            startHomeUrl = "";
        }
        this.startHomeUrl = startHomeUrl;
        this.column = column;
        if (headers == null) {
            headers = new HashMap<>();
        }

    }

    @Override
    public JSONObject getColumnOption() {
        return column;
    }

    @Override
    public String getProp() {
        return column.getString("prop");
    }

    public static boolean strIsJson(String str) {
        if (StringUtils.isAllBlank(str)) {
            return false;
        }
        str = str.trim();
        if (str.length() < 2) {
            return false;
        }
        return JSON.isValid(str);
    }


    public static boolean objIsJson(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj instanceof JSON) {
            return true;
        }
        if (obj instanceof String && strIsJson((String) obj)) {
            return true;
        }
        try {
            JSONObject.toJSONString(obj);
            return true;
        } catch (Exception e) {
            log.error("obj 无法转换问json", e);
            return false;
        }
    }

    public static JSONArray objectToJSONArray(Object value) {
        JSONArray jsonArray = null;
        if (!objIsJson(value)) {
            return null;
        }
        if (value instanceof String) {
            jsonArray = JSONArray.parseArray((String) value);
        } else if (value instanceof JSONArray) {
            jsonArray = (JSONArray) value;
        } else if (value instanceof Collection) {
            jsonArray = JSONArray.from(value);
        } else if (value.getClass().isArray()) {
            jsonArray = JSONArray.from(value);
        }
        return jsonArray;
    }
}
